<template>
  <div class="admin-page">
    <!--列表页 页面头部 -->
    <div class="page-header">
      <div class="page-title">
        <h2>{{ pageTitle }}</h2>
        <span class="page-description">{{ pageDescription }}</span>
      </div>
      
      <!-- 操作按钮区域 -->
      <div class="page-actions" v-if="businessData.length > 0 || add > 0">
        <el-button v-if="add > 0" type="primary" icon="Plus" @click="handleAdd">
          {{ anbiaoti || '新增' }}
        </el-button>
        <el-button 
          v-if="selectedRows.length > 0" 
          type="danger" 
          icon="Delete" 
          @click="handleBatchDelete"
        >
          批量删除 ({{ selectedRows.length }})
        </el-button>
        <!-- <el-button type="success" icon="Download" @click="handleExport">
          导出
        </el-button> -->
        <el-button type="warning" icon="Refresh" @click="handleRefresh">
          刷新
        </el-button>
      </div>
    </div>

    <!-- 搜索筛选区域 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="关键字">
          <el-input 
            v-model="searchForm.key" 
            placeholder="查询" 
            clearable 
            style="width: 200px"
          />
        </el-form-item>
        
        <!-- 动态查询条件 -->
        <el-form-item 
          v-for="(item, index) in keyobj" 
          :key="index" 
          :label="item.cn_name"
        >
          <!-- 选择参数类型 -->
          <el-select 
            v-if="item.ctype === '选择参数'"
            v-model="item.tishi" 
            :placeholder="item.tishi || ('查询' + item.cn_name)" 
            clearable 
            style="width: 150px"
            @click="xzDanCanShu(item, index)"
          >
            <el-option 
              v-for="option in item.options || []" 
              :key="option.value" 
              :label="option.label" 
              :value="option.value"
            />
          </el-select>
          
          <!-- 输入参数类型 -->
          <el-input 
            v-else
            v-model="item.tishi" 
            :placeholder="'查询' + item.cn_name" 
            clearable 
            style="width: 150px"
          />
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleSearch">
            查询
          </el-button>
          <el-button icon="RefreshRight" @click="handleReset">
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格区域 -->
    <el-card class="table-card" v-loading="loading">
      <!-- 如果有业务数据，显示后台管理风格的表格 -->
      <div v-if="businessData.length > 0" class="table-container">
        <!-- 表格工具栏 -->
        <div class="table-toolbar">
          <div class="toolbar-left">
            <span class="total-count">共 {{ recordCount }} 条记录，每页 {{ pageSize }} 条</span>
          </div>
          <div class="toolbar-right">
            <el-button-group>
              <el-button 
                :type="tableView === 'table' ? 'primary' : ''" 
                icon="Grid" 
                @click="tableView = 'table'"
              >
                表格视图
              </el-button>
              <el-button 
                :type="tableView === 'card' ? 'primary' : ''" 
                icon="Files" 
                @click="tableView = 'card'"
              >
                卡片视图
              </el-button>
            </el-button-group>
          </div>
        </div>

        <!-- 表格视图 -->
        <el-table 
          v-if="tableView === 'table'"
          :data="businessData" 
          border 
          stripe 
          style="width: 100%"
          @selection-change="handleSelectionChange"
          @sort-change="handleSortChange"
          @row-click="handleView"
          class="clickable-table"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column type="index" label="序号" width="60" />
          
          <!-- 主要信息列 -->
          <el-table-column prop="dbiaoti" label="标题" min-width="200" show-overflow-tooltip>
            <template #default="{ row }">
              <div class="title-cell">
                <el-link type="primary" @click.stop="handleView(row)" :underline="false">
                  {{ row.dbiaoti }}
                </el-link>
                <el-tag 
                  v-if="row.xbiaoti" 
                  :type="getStatusType(row.ztyw)" 
                  size="small"
                  class="status-tag"
                >
                  {{ row.xbiaoti }}
                </el-tag>
              </div>
            </template>
          </el-table-column>
          
          <!-- 详细信息列 -->
          <el-table-column label="详细信息" min-width="300">
            <template #default="{ row }">
              <div class="detail-cell">
                <div v-for="(item, index) in row.hlist" :key="index" class="detail-item">
                  {{ item.neirong }}
                </div>
              </div>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页器 -->
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="pageNumber"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="recordCount"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
      
      <!-- 如果都没有数据 -->
      <el-empty v-else description="暂无数据" />
    </el-card>

    <!-- 选择参数弹窗 -->
    <el-dialog 
      v-model="selectDialogVisible" 
      title="请选择" 
      width="60%" 
      @close="handleSelectDialogClose"
    >
      <div class="select-dialog-content">
        <!-- 搜索框 -->
        <el-form :model="selectForm" inline style="margin-bottom: 16px;">
          <el-form-item>
            <el-input 
              v-model="selectForm.keyinput" 
              placeholder="请输入搜索关键字" 
              clearable
              style="width: 300px"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleSelectSearch">
              查询
            </el-button>
          </el-form-item>
        </el-form>

        <!-- 选择列表 -->
        <el-table 
          :data="xzlist" 
          @row-click="handleSelectItem"
          style="cursor: pointer;"
          max-height="400"
        >
          <el-table-column prop="biaoti" label="标题" min-width="150" />
          <el-table-column label="详细信息" min-width="200">
            <template #default="{ row }">
              <div v-for="(item, index) in row.hlist" :key="index" class="select-detail">
                {{ item }}
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>

    <!-- 底部操作按钮 -->
    <div v-if="anlist.length > 0" class="bottom-actions">
      <el-button-group>
        <el-button 
          v-for="(item, index) in anlist" 
          :key="index"
          :type="getActionButtonType(item.ctype)"
          :icon="getActionButtonIcon(item.ctype)"
          @click="handleAction(item)"
        >
          {{ item.biaoti }}
        </el-button>
      </el-button-group>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import request, { getApiPath } from '@/utils/request'
import { Base64 } from 'js-base64'

// 路由和状态管理
const route = useRoute()
const router = useRouter()

// 响应式数据
const businessData = ref([])
const loading = ref(false)
const tableView = ref('table')
const pageNumber = ref(1)
const pageSize = ref(20)
const recordCount = ref(0)
const selectedRows = ref([])

// 业务相关数据
const anlist = ref([])
const anbiaoti = ref('')
const add = ref(0)
const keyobj = ref([])
const cxlx = ref(0)
const faid = ref(0)
const liuchengbh = ref('')

// 搜索表单
const searchForm = ref({
  key: '',
  cx_yewuy: '',
  cx_kehulx: ''
})

// 选择参数相关
const selectDialogVisible = ref(false)
const selectForm = ref({
  keyinput: ''
})
const xzlist = ref([])
const currentSelectIndex = ref(0)
const currentSelectObj = ref({})

// 页面标题 (根据实际路由参数动态生成，类似uniapp)
const pageTitle = computed(() => {
  // 从路由参数或动态菜单获取实际标题
  if (route.params.category && route.params.item) {
    return decodeURIComponent(route.params.item) || '列表页面'
  }
  
  // 检查是否有传入的标题参数
  if (route.query.title) {
    return decodeURIComponent(route.query.title)
  }
  
  return '合同流程列表'
})

const pageDescription = computed(() => {
  return `管理和维护${pageTitle.value}相关数据`
})

// 获取状态类型
const getStatusType = (status) => {
  const typeMap = {
    'dtj': 'danger',    // 待提交
    'dsp': 'warning',   // 待审批
    'yjj': 'danger',    // 已拒绝
    'dcl': 'info',      // 待处理
    'dsp_xtfq': 'success', // 审批通过
    'ywc': 'info'       // 已完成
  }
  return typeMap[status] || 'info'
}

// 获取操作按钮类型
const getActionButtonType = (ctype) => {
  const typeMap = {
    'fanhui': 'default',
    'shouye': 'primary',
    'shuaxin': 'success',
    'topage': 'warning',
    'gengduo': 'info'
  }
  return typeMap[ctype] || 'default'
}

// 获取操作按钮图标
const getActionButtonIcon = (ctype) => {
  const iconMap = {
    'fanhui': 'ArrowLeft',
    'shouye': 'House',
    'shuaxin': 'Refresh',
    'topage': 'Right',
    'gengduo': 'More'
  }
  return iconMap[ctype] || ''
}

// 事件处理方法
const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

const handleSortChange = ({ column, prop, order }) => {
  console.log('排序变化:', { column, prop, order })
}

const handleSearch = () => {
  pageNumber.value = 1
  fetchBusinessData()
}

const handleReset = () => {
  searchForm.value = {
    key: '',
    cx_yewuy: '',
    cx_kehulx: ''
  }
  keyobj.value.forEach(item => {
    item.tishi = ''
  })
  pageNumber.value = 1
  fetchBusinessData()
}

const handleSizeChange = (newSize) => {
  pageSize.value = newSize
  pageNumber.value = 1
  fetchBusinessData()
}

const handleCurrentChange = (newPage) => {
  pageNumber.value = newPage
  fetchBusinessData()
}

const handleAdd = () => {
  // 完全按照uniapp的toadd逻辑跳转到添加页面
  const addUrl = `/business/hetonglcxq_edit/hetonglcxq_edit`
  
  // 生成唯一的tabId用于新增页面
  const tabId = `add_${Date.now()}`
  
  // 生成动态标题
  const dynamicTitle = `新增${anbiaoti.value || pageTitle.value || '数据'}`
  
  const addParams = {
    faid: faid.value,
    cxlx: cxlx.value,
    liuchengbh: liuchengbh.value,
    ctype: 'add',
    tabId: tabId,
    title: encodeURIComponent(dynamicTitle)
  }
  
  console.log('uniapp风格新增跳转:', addUrl, addParams)
  router.push({ path: addUrl, query: addParams })
}

const handleView = (row) => {
  // 完全按照uniapp的toUrl_xq逻辑跳转到详情页面
  const detailUrl = `/business/hetonglcxq/hetonglcxq`
  
  // 生成唯一的tabId，用于区分不同的详情页面实例
  const tabId = `detail_${row.id || 0}_${Date.now()}`
  
  // 生成动态标题，包含关键信息
  let dynamicTitle = '详情'
  if (row.dbiaoti) {
    dynamicTitle = `${row.dbiaoti}详情`
  } else if (row.biaoti) {
    dynamicTitle = `${row.biaoti}详情`
  } else if (pageTitle.value) {
    dynamicTitle = `${pageTitle.value}详情`
  }
  
  const detailParams = {
    faid: faid.value || 0,
    id: row.id || 0,
    cxlx: cxlx.value || 0,
    liuchengbh: liuchengbh.value || '',
    tabId: tabId,  // 添加唯一标识
    title: encodeURIComponent(dynamicTitle)  // 添加动态标题
  }
  
  console.log('uniapp风格详情跳转:', detailUrl, detailParams)
  router.push({ path: detailUrl, query: detailParams })
}

const handleBatchDelete = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请先选择要删除的数据')
    return
  }
  
  ElMessageBox.confirm(
    `确定要删除选中的 ${selectedRows.value.length} 条记录吗？`,
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    ElMessage.success('删除成功')
    selectedRows.value = []
    fetchBusinessData()
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

const handleExport = () => {
  ElMessage.success('导出功能开发中...')
}

const handleRefresh = () => {
  fetchBusinessData()
}

// 选择参数相关方法
const xzDanCanShu = async (css, index) => {
  console.log('xzDanCanShu:', css, index)
  currentSelectObj.value = css
  currentSelectIndex.value = index
  
  const bs64_cs = {
    wtype: css.wtype,
    key: selectForm.value.keyinput || '',
    openid: localStorage.getItem('openid') || "17524180246839845722"
  }
  
  const cs = {
    ctype: 'app_xuanze_canshu',
    bs64_cs: Base64.encode(JSON.stringify(bs64_cs)),
    bs64_obj: '',
    bs64_list: '',
    ids: '',
    faid: faid.value
  }
  
  try {
    const res = await request.post(getApiPath(cs.ctype), { canshu: cs })
    console.log('选择参数响应:', res)
    
    if (res && res.shuzu) {
      xzlist.value = res.shuzu
      selectDialogVisible.value = true
    }
  } catch (error) {
    console.log('获取选择参数失败:', error)
  }
}

const handleSelectSearch = () => {
  xzDanCanShu(currentSelectObj.value, currentSelectIndex.value)
}

const handleSelectItem = (row) => {
  console.log('选择项目:', row)
  keyobj.value[currentSelectIndex.value].tishi = row.obj.name_1
  selectDialogVisible.value = false
  
  if (keyobj.value[currentSelectIndex.value].istijiao) {
    fetchBusinessData()
  }
}

const handleSelectDialogClose = () => {
  selectDialogVisible.value = false
}

const handleAction = (item) => {
  console.log('处理底部操作按钮:', item)
  
  switch (item.ctype) {
    case 'fanhui':
      router.back()
      break
    case 'shouye':
      router.push('/dashboard')
      break
    case 'shuaxin':
      ElMessage.success('刷新成功')
      fetchBusinessData()
      break
    case 'topage':
      // 完全按照uniapp的toPages逻辑跳转到指定页面
      const targetFaid = item.an_faid || faid.value
      const targetUrl = item.url || '/business/hetonglcxq_edit/hetonglcxq_edit'
      
      // 生成唯一的tabId
      const tabId = `action_${item.biaoti || 'page'}_${Date.now()}`
      
      // 生成动态标题
      const dynamicTitle = item.biaoti || '操作页面'
      
      const targetParams = {
        faid: targetFaid,
        cxlx: cxlx.value,
        liuchengbh: liuchengbh.value,
        ctype: 'add',
        tabId: tabId,
        title: encodeURIComponent(dynamicTitle)
      }
      
      console.log('uniapp风格toPages跳转:', targetUrl, targetParams)
      router.push({ path: targetUrl, query: targetParams })
      break
    case 'gengduo':
      ElMessage.info('更多操作功能')
      break
    default:
      ElMessage.info(`执行操作: ${item.biaoti}`)
  }
}

// 获取业务数据 (完全按照uniapp的getShuju逻辑)
const fetchBusinessData = async () => {
  try {
    loading.value = true
    console.log('=== 开始获取业务数据 (uniapp风格) ===')
    
    // 完全按照uniapp的onLoad逻辑处理参数
    let options = { ...route.query }
    
    // 检查是否有cs参数（与uniapp的onLoad一致）
    if (options.cs) {
      try {
        const decodedCs = decodeURIComponent(options.cs)
        const csParams = JSON.parse(decodedCs)
        console.log('从cs参数解析 (uniapp风格):', csParams)
        
        // 完全按照uniapp的逻辑设置参数
        pageNumber.value = csParams.number || 1
        cxlx.value = Number(csParams.cxlx) || 0
        searchForm.value.key = csParams.key || ''
        faid.value = Number(csParams.faid) || 0
        liuchengbh.value = csParams.liuchengbh || ''
      } catch (error) {
        console.log('解析cs参数失败:', error)
      }
    }
    
    // 从直接URL参数获取（与uniapp onLoad逻辑一致）
    if (options.faid) faid.value = Number(options.faid)
    if (options.cxlx) cxlx.value = Number(options.cxlx)
    if (options.liuchengbh !== undefined) liuchengbh.value = options.liuchengbh
    if (options.key) searchForm.value.key = options.key
    if (options.pageNumber) pageNumber.value = Number(options.pageNumber)
    
    console.log('uniapp风格参数:', { faid: faid.value, cxlx: cxlx.value, liuchengbh: liuchengbh.value })
    // 设置默认值（与uniapp保持一致）
    if (!faid.value) faid.value = 560602715
    if (!cxlx.value) cxlx.value = 101
    
    // 完全按照uniapp的getShuju构建请求参数
    const bs64_cs = {
      dtype: '',
      pagenumber: pageNumber.value,  // 对应uniapp的this.pageNumber
      id: 0,
      key: searchForm.value.key,
      yewuy: localStorage.getItem('username') || '常露',  // 对应uniapp的this.user_zsxm
      openid: localStorage.getItem('openid') || "17524180246839845722",  // 对应uniapp的this.deviceId
      cxlx: cxlx.value,  // 对应uniapp的this.cxlx
      kehusbbh: '',
      cx_kehulx: searchForm.value.cx_kehulx || '',
      cx_yewuy: searchForm.value.cx_yewuy || '',
      liuchengbh: liuchengbh.value  // 对应uniapp的this.liuchengbh
    }
    // 添加动态查询条件（与uniapp完全一致）
    if (keyobj.value.length > 0) {
      keyobj.value.forEach(item => {
        if (item.en_name && item.tishi) {
          bs64_cs[item.en_name] = item.tishi
        }
      })
    }
    
    // 特殊URL处理（与uniapp一致）
    let apiUrl = undefined
    if (bs64_cs.cxlx === 901 || bs64_cs.cxlx === 902) {
      apiUrl = 'https://fdddzq.haozskj.com/xcx/ajax/Ajax_apppost.ashx'
      bs64_cs.xulieh = localStorage.getItem('xulieh') || ''
    }
    
    const cs = {
      ctype: 'app_zlxt_lb',  // 与uniapp完全一致的接口类型
      bs64_cs: Base64.encode(JSON.stringify(bs64_cs)),
      bs64_obj: '',
      bs64_list: '',
      faid: faid.value,
      ids: ''
    }
    
    console.log('发送请求参数 (uniapp风格):', cs)
    console.log('bs64_cs解码 (uniapp风格):', bs64_cs)
    
    const res = await request.post(apiUrl || getApiPath(cs.ctype), { canshu: cs })
    console.log('业务数据响应:', res)
    
    if (res && res.leixing === 'ok') {
      businessData.value = res.shuzu || []
      pageSize.value = res.pageSize || 20
      recordCount.value = res.recordCount || 0
      anlist.value = res.anlist || []
      anbiaoti.value = res.anbiaoti || '新增'
      add.value = res.add || 0
      
      if (keyobj.value.length === 0 && res.cx_list) {
        keyobj.value = res.cx_list
      }
      
      if (res.ckbiaoti) {
        document.title = res.ckbiaoti
      }
      
      console.log('成功获取业务数据:', businessData.value.length, '条记录')
      ElMessage.success(`成功加载 ${businessData.value.length} 条数据`)
    } else {
      console.log('业务数据获取失败:', res)
      ElMessage.error(res?.msg || '获取数据失败')
      businessData.value = []
    }
  } catch (error) {
    console.log('获取业务数据失败:', error)
    ElMessage.error('获取数据失败')
    businessData.value = []
  } finally {
    loading.value = false
  }
}

// 组件挂载 (完全按照uniapp的onLoad逻辑)
onMounted(async () => {
  console.log('=== uniapp风格列表页面初始化 ===')
  console.log('route.query:', route.query)
  console.log('route.params:', route.params)
  
  // 检查是否为动态路由访问
  if (route.params.category && route.params.item) {
    console.log('动态路由访问 (uniapp风格):', {
      category: route.params.category,
      item: route.params.item
    })
  }
  
  await fetchBusinessData()
  console.log('=== uniapp风格列表页面初始化完成 ===')
})

// 监听路由参数变化 - 解决从菜单栏点击不请求数据的问题
watch(() => route.query, async (newQuery, oldQuery) => {
  console.log('=== 合同流程列表路由参数变化，重新获取数据 ===')
  console.log('新参数:', newQuery)
  console.log('旧参数:', oldQuery)
  
  // 如果参数有变化，重新获取数据
  if (JSON.stringify(newQuery) !== JSON.stringify(oldQuery)) {
    await fetchBusinessData()
  }
}, { immediate: false })

// 监听路由路径变化 - 确保页面切换时重新加载数据
watch(() => route.path, async (newPath, oldPath) => {
  console.log('=== 合同流程列表路由路径变化 ===')
  console.log('新路径:', newPath)
  console.log('旧路径:', oldPath)
  
  // 如果是进入合同流程列表页面，重新获取数据
  if (newPath.includes('/hetonglclb/hetonglclb') && newPath !== oldPath) {
    await fetchBusinessData()
  }
}, { immediate: false })
</script>

<style scoped>
/* 继承 dynamic/index.vue 的样式 */
.admin-page {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: calc(100vh - 60px);
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 0 4px;
}

.page-title h2 {
  margin: 0 0 4px 0;
  color: #303133;
  font-size: 20px;
  font-weight: 600;
}

.page-description {
  color: #606266;
  font-size: 14px;
}

.page-actions {
  display: flex;
  gap: 8px;
}

.search-card {
  margin-bottom: 16px;
}

.search-card :deep(.el-card__body) {
  padding: 16px 20px;
}

.table-card {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.12), 0 0 6px rgba(0, 0, 0, 0.04);
}

.table-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  border-bottom: 1px solid #ebeef5;
  background: #fafafa;
}

.total-count {
  font-size: 14px;
  color: #606266;
  font-weight: 500;
}

.table-container {
  background: white;
}

.clickable-table :deep(.el-table__body-wrapper tbody tr) {
  cursor: pointer;
  transition: all 0.2s ease;
}

.clickable-table :deep(.el-table__body-wrapper tbody tr:hover) {
  background-color: #ecf5ff !important;
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.title-cell {
  display: flex;
  flex-direction: column;
  gap: 8px;
  padding: 8px 0;
}

.title-cell .el-link {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.status-tag {
  align-self: flex-start;
  font-size: 12px;
  padding: 2px 8px;
  border-radius: 4px;
}

.detail-cell {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.detail-item {
  color: #818181;
  font-size: 13px;
  line-height: 1.4;
}

.pagination-container {
  padding: 16px 20px;
  border-top: 1px solid #ebeef5;
  background: #fafafa;
  display: flex;
  justify-content: center;
}

.bottom-actions {
  position: fixed;
  bottom: 20px;
  right: 20px;
  z-index: 1000;
  background: white;
  padding: 12px;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  border: 1px solid #ebeef5;
}
</style>
